package com.my.lock.v26;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by ZhongGang
 * at 2018/9/17 16:41
 */
public class MCSLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(MCSLock.class);

    private AtomicReference<Node> tail = new AtomicReference<>(null);
    private ThreadLocal<Node> myNode = new ThreadLocal<Node>() {
        @Override
        protected Node initialValue() {
            return new Node();
        }
    };

    public void lock() {
        Node qnode = myNode.get();
        Node pred = tail.getAndSet(qnode);
        if (pred != null) {
            qnode.locked = true;
            pred.next = qnode;

            // wait until predecessor gives up the lock
            while (qnode.locked) {
            }
        }

        LOGGER.info("locked by {}", Thread.currentThread().getName());
    }

    public void unlock() {
        Node qnode = myNode.get();
        if (qnode.next == null) {
            if (tail.compareAndSet(qnode, null))
                return;

            // wait until predecessor fills in its next field
            while (qnode.next == null) {
            }
        }
        qnode.next.locked = false;
        qnode.next = null;
    }

    class Node {
        volatile boolean locked = false;
        volatile Node next = null;
    }

    public static void main(String[] args) {
        MCSLock lock = new MCSLock();

        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        lock.lock();

                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new UnsupportedOperationException("Not yet implemented!");
                    } finally {
                        lock.unlock();
                    }
                }
            }).start();
        }
    }
}
